<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="submit">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in list" :key="item.id">
          <td>{{index+1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(list[index])">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
// 一定一定要记得 数据驱动视图
export default {
  data() {
    return {
      list: [],
      name: '',
      age: '',
      gender: '男',
      sty: 'add',
      nowRow: {},
    }
  },
  methods: {
    edit(row) {
      this.sty = 'edit'
      this.gender = row.gender
      this.name = row.name
      this.age = row.age
      this.nowRow = row
    },
    submit() {
      if (this.name === '' || this.age === '') {
        alert('姓名年龄不能为空')
      } else if (this.sty === 'edit') {
        this.list.forEach((item) => {
          if (item.id === this.nowRow.id) {
            item.name = this.name
            item.age = this.age
            item.gender = this.gender
          }
        })
        alert('修改成功')
      } else {
        this.list.push({
          id: this.list.length ? this.list.length + 1 : 0,
          name: this.name,
          age: this.age,
          gender: this.gender,
        })
        alert('添加成功')
      }
      this.name = ''
      this.age = ''
      this.gender = '男'
      this.type = 'add'
    },
    del(id) {
      this.list = this.list.filter((item) => item.id !== id)
      alert('删除成功')
    },
  },
}
</script>
